package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoGroupMessageEvent;
import com.rw.coco.handler.message.reply.GroupReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.handler.message.reply.handler.command.sender.ObSender;
import com.rw.coco.handler.message.reply.handler.command.sender.RollSender;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;

/**
 * 暗骰Roll点处理
 * 指令：.rh
 */
public class PrivateRollHandler extends GroupReplyHandler {
    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    public PrivateRollHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String command = cocoCommandConfig.commandProp.get(CocoCommandConfig.PRIVATE_ROLL);
        this.matcher = CommandMatcher.of(command);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_PRIVATE_ROLL);
    }

    @Override
    protected boolean groupTrigger(CocoGroupMessageEvent groupEvent) {
        String message = groupEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    protected void groupHandler(CocoGroupMessageEvent groupEvent) {
        DiceReply diceReply = groupEvent.getReplyApi().getDiceReply();

        // 获取roll点的发送器
        RollSender sender = new RollSender(groupEvent, matcher.subTrim(groupEvent.getMessage()));

        if (sender.success()) {
            // 正常回复
            reply(groupEvent, sender);
        } else if (sender.getExpressionException() != null) {
            // 表达式解析失败
            groupEvent.sendBack(diceReply.expressionException(sender.getExpressionException()));
        } else if (sender.getNumberOverflowException() != null) {
            // 数字超大
            groupEvent.sendBack(diceReply.numberOverflowException(groupEvent));
        }
    }

    @Override
    public int priority() {
        return matcher.priority();
    }

    /**
     * 经过解析运算之后，得到的结果回复给发送人
     *
     * @param sender 发送器
     */
    private static void reply(CocoGroupMessageEvent event, RollSender sender) {
        // 获取事件
        DiceReply diceReply = event.getReplyApi().getDiceReply();

        // 获取回复
        String reply = diceReply.privateRollReply(event, sender.getParser().getName(), sender.getExpression());
        String result = diceReply.privateRollResult(event, sender.getParser().getName(), sender.getExpression());

        // 回复
        event.sendBack(reply);
        event.sendBackSender(result);

        // 对群内所有旁观的人发送结果
        ObSender obSender = new ObSender(event);
        obSender.sendAllObResult(result);
    }
}
